require('zone.js');

const ARule = require('./ARule');

class StickyRule extends ARule {

    sessionMap = new Map();

    /**
     * 通过粘性会话规则选择一个服务节点
     * @param {String} service 
     * @param {Array<String>} nodes 
     * @returns 服务节点
     */
    choose(service, nodes) {
        let sessionId = Zone.current.sessionId;
        if (!sessionId)
            sessionId = "unknown";

        let node = this.sessionMap.get(`${sessionId}:${service}`);
        if (node && nodes.some(i => i == node)) {
            console.debug(`${sessionId} sticky choose : ${service} ${node}`);
            return node;
        }

        console.debug(`${sessionId} do sticky choose : ${service}`);

        node = nodes[Math.floor(Math.random() * nodes.length)];
        console.debug(`${sessionId} sticky choose : ${service} ${node}`);
        this.sessionMap.set(`${sessionId}:${service}`, node);

        return node;
    }
}


module.exports = StickyRule;